package com.mab.mall.search.thread;

import java.util.concurrent.*;

/**
 * 异步调用后---回调方法
 */
public class CompletableFutureDemo2 {

    // 自定义线程池
    private static ThreadPoolExecutor executor = new ThreadPoolExecutor(5
            ,10
            ,10
            , TimeUnit.SECONDS
            , new LinkedBlockingQueue<>(100)
            , Executors.defaultThreadFactory()
            , new ThreadPoolExecutor.AbortPolicy()
            );

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        // 异步对象

        CompletableFuture<Integer> supplyAsync = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程执行开始---->");
            int i = 10 / 5;
            System.out.println("线程执行结束--------");
            return i;
        }, executor).handle((res,exec)->{
            // res异步处理结果，， exec抛出异常信息
            // 可以对异步处理结果进行修改
            System.out.println("handler.res="+res);
            System.out.println("handler.exec="+exec);
            return res*10;
        });
        System.out.println("supply线程执行结果--->"+supplyAsync.get());


        CompletableFuture<Integer> async = CompletableFuture.supplyAsync(() -> {
            System.out.println("线程执行开始---->");
            int i = 10 / 0;
            System.out.println("线程执行结束--------");
            return i;
        }, executor).whenCompleteAsync((res,exec)->{
            // res异步处理后及如果, exec处理抛出的异常信息
            System.out.println("res="+res);
            System.out.println("exec="+exec);
        }).exceptionally((exec)->{
            // 异常处理，可以修改返回结果
            // 如果出现异常执行此方法，没有异常不执行
            System.out.println("异常exec="+exec);
            return 20;
        });
        System.out.println("supply线程执行结果--->"+async.get());

    }

}
